package edu.pku.sei.transformation.editor.controller.commands.node;

import java.util.List;

import org.eclipse.gef.commands.Command;

import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.core.MetaPackage;
import edu.pku.sei.modeler.model.structure.MetaDiagram;

public class DiagramNodeDeleteCommand extends Command {
	private MetaModelElement node;
	private MetaDiagram diagram;
	private MetaPackage pkg;

	public DiagramNodeDeleteCommand(MetaModelElement node, MetaDiagram father) {
		this.node = node;
		this.diagram = father;
	}

	@Override
	public boolean canExecute() {
		if (node == null || diagram == null) {
			return false;
		} else
			return super.canExecute();
	}

	@Override
	public void execute() {
		pkg = findPackage(node.getModel(), diagram);
		if (pkg != null)
			pkg.getOtherElements().remove(node);
	}

	@Override
	public void undo() {
		if (pkg != null)
			pkg.getOtherElements().add(node);
	}

	protected MetaPackage findPackage(MetaModel model, MetaDiagram diagram) {
		if (model == null || diagram == null)
			return null;
		List pkgs = model.getPackages();
		for (int i = 0; i < pkgs.size(); i++) {
			MetaPackage pkg = (MetaPackage) pkgs.get(i);
			MetaPackage result = findPackage(pkg, diagram);
			if (result != null)
				return result;
		}
		return null;
	}

	protected MetaPackage findPackage(MetaPackage pkg, MetaDiagram diagram) {
		if (pkg == null)
			return null;
		List diags = pkg.getDiagrams();
		for (int i = 0; i < diags.size(); i++) {
			if (diags.get(i) == diagram)
				return pkg;
		}
		List pkgs = pkg.getSubPackages();
		for (int i = 0; i < pkgs.size(); i++) {
			MetaPackage subPkg = (MetaPackage) pkgs.get(i);
			MetaPackage result = findPackage(subPkg, diagram);
			if (result != null)
				return result;
		}
		return null;
	}

}
